package mrusanov.staff

import java.util.{ GregorianCalendar, Calendar, Date }
import mrusanov.team.Club

object Contract {
	def createContractForClubEmployee(startYear: Date, years: Int): Contract = {
		// TODO rewrite
		new Contract(startYear, Vector.fill(years)(0))
	}
}

class Contract(startYear: Date, val moneyPerYear: Vector[Int]) {

	def yearAndSalaryMap: Map[Int, Int] = {
		val calendar = Calendar.getInstance()
		calendar.setTime(startYear)

		val start = calendar.get(Calendar.YEAR)
		val startStream = Stream.from(start)
		val result = startStream.zip(moneyPerYear)
		result.toMap
	}

	def salaryInYear(currentYearDate: Date): Int = {
		val startCalendar = Calendar.getInstance()
		startCalendar.setTime(startYear)
		val startYearInt = startCalendar.get(Calendar.YEAR)

		val currentCalendar = Calendar.getInstance()
		currentCalendar.setTime(currentYearDate)
		val currentYearInt = currentCalendar.get(Calendar.YEAR)

		val index = currentYearInt - startYearInt
		moneyPerYear(index)
	}

	def contractYearsLeft(now: Date): Int = {
		val calendar = Calendar.getInstance()
		calendar.setTime(now)
		val currentYear = calendar.get(Calendar.YEAR)

		yearAndSalaryMap.filter(_._1 > currentYear).size
	}

	def contractSumLeft(now: Date): Int = {
		val passedYears = yearsDifference(startYear, now)

		val yearsLeft = moneyPerYear.drop(passedYears)

		if (yearsLeft.size == 0) {
			return 0
		}

		val partlyPayedYear = yearsLeft(0)
		val fullPayedYears = yearsLeft.drop(1)

		partlyPay(partlyPayedYear, now) + fullPayedYears.foldLeft(0)(_ + _)
	}

	def isOver(now: Date) = yearsDifference(startYear, now) >= moneyPerYear.size

	private def partlyPay(yearSalary: Int, now: Date): Int = {
		val calendar = new GregorianCalendar()
		calendar.setTime(now)
		val dayOfYear = calendar.get(Calendar.DAY_OF_YEAR)
		val leapYear = calendar.isLeapYear(calendar.get(Calendar.YEAR))
		val daysInYear = if (leapYear) 366 else 365
		(yearSalary.toDouble * (daysInYear - dayOfYear) / daysInYear).round.toInt
	}

	private def yearsDifference(smaller: Date, bigger: Date): Int = {
		val smallerCal = Calendar.getInstance()
		smallerCal.setTime(smaller)

		val biggerCal = Calendar.getInstance()
		biggerCal.setTime(bigger)

		biggerCal.get(Calendar.YEAR) - smallerCal.get(Calendar.YEAR)
	}
}
